package com.demo.security.cloud.servicecenter.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    /**
     * 和认证服务器UUA中的Client C1配置的ResourceID对应
     */
    public static final String RESOURCE_ID = "res1";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {

        resources.resourceId(RESOURCE_ID)
                // 验证令牌的服务
                .tokenServices(tokenServices())
                .stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/order/hello").permitAll()
                // 所有的访问必须要有scope为All
                .antMatchers("/order/r/*").access("#oauth2.hasScope('all')")
                .and().csrf().disable()
                // spring security不会创建，也不会使用。
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Bean
    public ResourceServerTokenServices tokenServices(){

        RemoteTokenServices tokenServices = new RemoteTokenServices();
        tokenServices.setClientId("c1");
        // 可以是所有加密的
        tokenServices.setClientSecret("ABC");
        // 在统一认证服务中开放的check_token
        tokenServices.setCheckTokenEndpointUrl("http://localhost:9002/oauth/check_token");
        return tokenServices;
    }
}
